import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STColumn, STColumnBadge, STComponent, STData, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFUISchema } from '@delon/form';
import { SearchDrawerService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicTableComponent } from 'src/app/routes/commom';
import { UsermanageService } from '../../../services/usercenter.service';
@Component({
  selector: 'app-Freight-components-user',
  styleUrls: ['../../../../commom/less/commom-table.less'],
  templateUrl: './user.component.html'
})
export class FreightComponentsUserComponent extends BasicTableComponent implements OnInit {
  schema: SFSchema = this.initSF();
  columns: STColumn[] = this.initST();

  @ViewChild('promoterModal', { static: false })
  promoterModal!: any;
  promotersTelephone = '';

  resourceStatus: any = 0;

  constructor(
    public service: UsermanageService,
    private modal: NzModalService,
    private router: Router,
    private ar: ActivatedRoute,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  search() {
    this.st?.load(1);
  }

  ngOnInit() {}

  beforeReq = (requestOptions: STRequestOptions) => {
    Object.assign(requestOptions.body, { certificationStatus: this.resourceStatus });
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...this.sf?.value
      });
      if (this.sf?.value.effectiveDate) {
        Object.assign(requestOptions.body, {
          time: {
            start: this.sf?.value.effectiveDate[0],
            end: this.sf?.value.effectiveDate[1]
          }
        });
      }
      delete requestOptions.body.effectiveDate;
      delete requestOptions.body.expand;
    }
    return requestOptions;
  };

  selectChange(e: any) {
    this.resourceStatus = e;
    this.st.load();
  }

  addPromoter(item?: any) {
    this.promotersTelephone = item?.promotersTelephone;
    const modal = this.modal.create({
      nzTitle: '推广业务员',
      nzContent: this.promoterModal,
      nzOnOk: () => {
        if (!!!this.promotersTelephone) {
          return false;
        }
        if (typeof this.promotersTelephone === 'string' && !/(^1\d{10}$)/.test(this.promotersTelephone)) {
          this.service.msgSrv.error('手机格式错误');
          return false;
        }
        this.service
          .request(this.service.$api_add_user_salesman, { userId: item.userId, mobile: this.promotersTelephone })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success(item?.promotersTelephone ? '添加推广员成功' : '修改推广员成功');
            }
            this.st.load();
          });
        return;
      }
    });
  }

  userAction(status: number, appUserId: Array<number>) {
    this.modal.warning({
      nzTitle: status === 1 ? '确定启用该用户吗？' : '确定冻结该用户吗？',
      nzContent:
        status === 1
          ? '启用后，该用户将恢复正常使用功能，请再次确认'
          : '停用后，该用户将被限制使用，不限于访问受限、无法发布货源等，请谨慎操作',
      nzOnOk: () => {
        this.service
          .request(this.service.$api_lock_or_free_user, {
            appUserId,
            freezeOrResume: !!!status,
            pageName: '货主员工列表'
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success(status === 1 ? '启用成功' : '冻结成功');
              this.st.reload();
            }
          });
      }
    });
  }

  exportList() {
    const params = { certificationStatus: this.resourceStatus, pageSize: -1 };
    if (this.sf) {
      Object.assign(params, {
        ...this.sf?.value
      });
    }
    this.service.downloadFile(this.service.$api_get_user_list_export, params);
  }

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        name: {
          title: '用户姓名',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },
        enterpriseName: {
          title: '企业名称',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },
        telephone: {
          title: '手机号',
          type: 'string',
          maxLength: 11,
          ui: {
            placeholder: '请输入'
          }
        },
        stateLocked: {
          type: 'string',
          title: '状态',
          enum: [
            { label: '全部', value: '' },
            { label: '正常', value: 0 },
            { label: '冻结', value: 1 }
          ],
          default: '',
          ui: {
            widget: 'select'
          }
        },
        promotersTelephone: {
          title: '推广业务员',
          type: 'string',
          maxLength: 11,
          ui: {
            placeholder: '请输入手机号'
          }
        },
        effectiveDate: {
          title: '申请时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
        } 
      },
      { title: '企业名称', className: 'text-center', index: 'enterpriseName' },
      { title: '项目名称', className: 'text-center', index: 'projectName' },
      { title: '用户姓名', className: 'text-center', index: 'name' },
      { title: '手机号', className: 'text-center', index: 'telephone' },
      { title: '身份证件号', className: 'text-center', index: 'certificateNumber' },
      { title: '常用服务', className: 'text-center', index: 'unifiedSocialCreditCode' },
      { title: '推广业务员', className: 'text-center', index: 'promotersTelephone', render: 'promotersTelephone' },
      { title: '申请时间', className: 'text-center', index: 'createTime', type: 'date' },
      {
        title: '状态',
        className: 'text-center',
        index: 'certificationStatus',
        type: 'badge',
        badge: {
          0: { text: '待审核', color: 'processing' },
          1: { text: '已成功', color: 'success' },
          2: { text: '已驳回', color: 'warning' }
        }
      },
      {
        title: '操作',
        width: '170px',
        className: 'text-center',
        buttons: [
          {
            text: '查看',
            click: (item: any) => {
              this.router.navigate(['./view', item.appUserId], { relativeTo: this.ar });
            },
            acl: { ability: ['USERCENTER-FREIGHT-USER-view'] }
          },
          {
            text: '冻结',
            iif: item => item.stateLocked === 0,
            click: (item: any) => this.userAction(0, [item.appUserId]),
            acl: { ability: ['USERCENTER-FREIGHT-USER-lock'] }
          },
          {
            text: '启用',
            iif: item => item.stateLocked === 1,
            click: (item: any) => this.userAction(1, [item.appUserId]),
            acl: { ability: ['USERCENTER-FREIGHT-USER-lock'] }
          }
        ]
      }
    ];
  }
}
